const url = require('url');
const got = require('@/utils/got');
const cheerio = require('cheerio');

function isComment(index, node) {
    return node.type === 'comment'
}
function isCss(index, node) {
    return node.type === 'style'
}

module.exports = async (ctx) => {
    let list = [];

    let today = new Date();
    if (today.getHours() < 8) {
        today = new Date(today.getTime() - 24*3600e3);
    }
    const twoDigit = (num) => num < 10 ? '0'+num : ''+num;
    const dateStr = `${today.getFullYear()}${twoDigit(today.getMonth()+1)}/${twoDigit(today.getDate())}`;

    const root_url = 'http://paper.people.com.cn/rmrb/';
    const nodeUrls = Object.keys([...new Array(1)]).map((k,i) =>
        `http://paper.people.com.cn/rmrb/pc/layout/${dateStr}/node_${twoDigit(i+1)}.html`
    );

    const responses = await Promise.all(nodeUrls.map(url => got({
        method: 'get',
        url,
    })));

    responses.forEach(resp => {
        const $ = cheerio.load(resp.data);
        const lst = $('a[id="pageLink"]');
        for(let i=0; i<lst.length; i++) {
            const it = $(lst[i]);
            list.push({
                title: it.text(),
                link: it.attr('href'),
            });
        }
    });

    const count = [];
    for (let i = 0; i < Math.min(list.length, 10); ++i) {
        count.push(i);
    }

    const items = await Promise.all(
        count.map((i) => {
            const item = list[i];
            const {link, title} = item;

            return ctx.cache.tryGet('rmrb_' + link, async () => {
                const nodeUrl = url.resolve(nodeUrls[0], link);
                const res = await got({ method: 'get',
                    url: nodeUrl
                });
                const content = cheerio.load(res.data);
                const listDetails = content('ul.news-list>li>a');
                return listDetails.map((inx,el) => ({
                    title: `${title.replace('：','')} - ${content(el).text()}`,
                    link: url.resolve(nodeUrl, content(el).attr('href')),
                })).get()
            });
        })
    );

    const itemDetails = await Promise.all(
        Array.prototype.concat.apply([], items).map((it) => {
            const {link, title} = it;

            return ctx.cache.tryGet('rmrb_' + link.replace('http://paper.people.com.cn/rmrb/',''), async () => {
                const pubDate = new Date(`${today.getFullYear()}/${twoDigit(today.getMonth()+1)}/${twoDigit(today.getDate())}` + ' 00:00:00 GMT+8').toUTCString();

                const res = await got({ method: 'get',
                    url: link
                }).catch((e) => {});

                if (res) {
                    const content = cheerio.load(res.data);
                    const post = content('div.article-box>div.article');
                    post.contents().filter(isComment).remove();
                    post.contents().filter(isCss).remove();

                    post.find('img[data-src]').each((_, ele) => {
                        ele = content(ele);
                        ele.attr('src', ele.attr('data-src'));
                        ele.removeAttr('class');
                        ele.removeAttr('data-src');
                    });

                    return {
                        title,
                        link,
                        pubDate,
                        description: post.html(),
                    };
                } else {
                    return null
                }
            })
        })
    );

    ctx.state.data = {
        title: '人民日报',
        link: root_url,
        item: itemDetails,
    };
};
